﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace JavaBatGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Java bat generator tool - Author mumau";
            if (args.Length <= 0)
            {
                Console.WriteLine("------------------------------------------------------");
                Console.WriteLine("--------Java bat generator tool - Author mumau--------");
                Console.WriteLine("------------------------------------------------------");
                RegistryKey appKey = Registry.ClassesRoot.OpenSubKey(@"Directory\background\shell\jbg");
                if (appKey != null)
                {
                    uninstallApp();
                }
                else
                {
                    installApp();
                }
            }
            else
            {
                generateBat(args[0]);
            }
        }

        private static void generateBat(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    var filesJavaClass = Directory.GetFiles(path, "*.class", SearchOption.AllDirectories);
                    if (filesJavaClass != null && filesJavaClass.Length > 0)
                    {
                        frmGenerator frm = new frmGenerator(filesJavaClass);
                        var rs = frm.ShowDialog();
                        if (rs == System.Windows.Forms.DialogResult.OK)
                        {
                            int i = 0;
                            foreach (var item in frm.SelectedFiles)
                            {
                                string curentPath = item.Replace(path, "").Replace(".class", "");
                                if (curentPath[0] == '\\')
                                {
                                    curentPath = curentPath.Substring(1);
                                }
                                if (curentPath.IndexOf('\\') == curentPath.LastIndexOf('\\'))
                                {
                                    string batContent = String.Format("java {0}\r\npause", curentPath.Replace("\\", "."));
                                    string batNameFile = Path.Combine(path, Path.GetFileName(item).Replace(".class", "") + ".bat");
                                    File.WriteAllText(batNameFile, batContent);
                                    i++;
                                }
                                else
                                {
                                    curentPath = Path.GetDirectoryName(item);
                                    if (curentPath.LastIndexOf("\\") > 0)
                                    {
                                        curentPath = curentPath.Substring(0, curentPath.LastIndexOf("\\"));
                                        string batContent = @"cd\";
                                        batContent += "\r\ncd " + curentPath;
                                        curentPath = item.Replace(curentPath, "").Replace(".class", "");
                                        if (curentPath[0] == '\\')
                                        {
                                            curentPath = curentPath.Substring(1);
                                        }
                                        batContent += "\r\ncls";
                                        batContent += String.Format("\r\njava {0}\r\npause", curentPath.Replace("\\", "."));
                                        string batNameFile = Path.Combine(path, Path.GetFileName(item).Replace(".class", "") + ".bat");
                                        File.WriteAllText(batNameFile, batContent);
                                        i++;
                                    }
                                }
                            }
                            MessageBox.Show("Created " + i + " .bat file.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("\nCan't find any .class file in this folder.");
                        Console.ReadKey();
                    }
                }
            }
            catch
            {
                Console.WriteLine("\nError was occurred, please try again.");
                Console.ReadKey();
            }
        }

        private static void installApp()
        {
            try
            {
                File.Copy(Assembly.GetExecutingAssembly().CodeBase.Substring(8).Replace("/", "\\"), Path.GetPathRoot(Environment.SystemDirectory) + "jbg.exe", true);
                var jbgReg = Registry.ClassesRoot.CreateSubKey(@"Directory\background\shell\jbg");
                var jbgCommandReg = Registry.ClassesRoot.CreateSubKey(@"Directory\background\shell\jbg\command");
                jbgReg.SetValue("", "&Generate .bat file");
                jbgCommandReg.SetValue("", "\"" + Path.GetPathRoot(Environment.SystemDirectory) + "jbg.exe\" \"%v\"");
                Console.WriteLine("Install completed");
                Console.ReadKey();
            }
            catch
            {
                Console.WriteLine("\nError was occurred, please try again or run as adminitrator permission.");
                Console.ReadKey();
            }
        }

        static void uninstallApp()
        {
            try
            {
                string cmd;
                while (true)
                {
                    Console.Write("[U]ninstall tool\r\n[R]epair tool\r\nYour choose: ");
                    cmd = Console.ReadLine().Trim();
                    if (cmd.Length == 1 && "uUrR".Contains(cmd))
                    {
                        break;
                    }
                    Console.WriteLine("Wrong select!");
                    Console.ReadKey();
                }
                if (cmd.ToLower() == "u")
                {
                    while (true)
                    {
                        Console.Write("Do you want to uninstall java bat generator tool? [Y/N]: ");
                        cmd = Console.ReadLine().Trim();
                        if (cmd.Length == 1 && "yYnN".Contains(cmd))
                        {
                            break;
                        }
                        Console.WriteLine("Wrong answer!");
                        Console.ReadKey();
                    }
                    if (cmd.ToLower() == "y")
                    {
                        Registry.ClassesRoot.DeleteSubKeyTree(@"Directory\background\shell\jbg");
                        Console.WriteLine("Remove completed");
                        Console.ReadKey();
                    }
                    else
                    {
                        Console.WriteLine("Bye bye.");
                        Console.ReadKey();
                    }
                }
                else
                {
                    File.Copy(Assembly.GetExecutingAssembly().CodeBase.Substring(8).Replace("/", "\\"), Path.GetPathRoot(Environment.SystemDirectory) + "jbg.exe", true);
                    Console.WriteLine("\r\nRepair completed.");
                    Console.ReadKey();
                }
            }
            catch
            {
                Console.WriteLine("\nError was occurred, please try again or run as adminitrator permission.");
                Console.ReadKey();
            }
        }
    }
}
